package com.cogent.dao.orm.impl;

import java.util.HashMap;
import java.util.Map;

import com.cogent.common.util.BaseUtil;
import com.cogent.common.util.MapUtil;
import com.cogent.dao.domain.TableInfoDomain;
import com.cogent.dao.facade.BussinessDaoFacade;
import com.cogent.dao.orm.IDGen;

public class CogentIDGenImpl implements IDGen {	
	private static Map CACHED_ID_MAP = new HashMap();
	
	private BussinessDaoFacade bussinessDaoFacade;
	
	public synchronized String getNextID(String tableName, TableInfoDomain tableInfoDomain) {
		String ret = "";
		if(tableInfoDomain.getIdtype() == 1) {
			tableName = tableName.toLowerCase();
			if(CACHED_ID_MAP.containsKey(tableName)) {
				int id = Integer.parseInt(MapUtil.getStringValue(CACHED_ID_MAP
						, tableName)) + 1;
				ret = "" + id;
				CACHED_ID_MAP.put(tableName, ret);
			}else {
				HashMap retMap = bussinessDaoFacade.getOneRow("SELECT MAX(id) as maxid from " + tableName);
				if(MapUtil.isEmpty(retMap, "maxid"))
					ret = "1";
				else
					ret = "" + (Integer.parseInt(MapUtil.getStringValue(retMap, "maxid")) + 1);
				CACHED_ID_MAP.put(tableName, ret);
			}
		} else
			ret = BaseUtil.genUUID();
		
		return ret;
	}

	public BussinessDaoFacade getBussinessDaoFacade() {
		return bussinessDaoFacade;
	}

	public void setBussinessDaoFacade(BussinessDaoFacade bussinessDaoFacade) {
		this.bussinessDaoFacade = bussinessDaoFacade;
	}
}
